using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using Microsoft.Health.Samples.PatientConnect.TreyResearch.HealthVaultAdapter;

namespace Microsoft.Health.Samples.PatientConnect.TreyResearch.TreyResearchScheduler
{
    public class ServiceInboundCalls
    {
        /// <summary>
        /// Returns calculated time in milliseconds.
        /// </summary>
        /// <returns>Timer value in milliseconds.</returns>
        public static long CalculateTimerValue()
        {
            TimeSpan timeSpan = new TimeSpan(SchedulerConfig.Days, SchedulerConfig.Hours, SchedulerConfig.Minutes, SchedulerConfig.Seconds);
            long timerValue = (long)timeSpan.TotalMilliseconds;
            return timerValue;
        }


        /// <summary>
        /// This method calls methods from ReadHealthVaultItemTypes class.
        /// </summary>
        public static void CallInboundMethods()
        {
            string logfileName = SchedulerConfig.LogFile;
            string practicesXmlFile = Path.GetFullPath(SchedulerConfig.PracticeXmlFilePath);
            string patientXmlFile = SchedulerConfig.PatientXmlFilePath;
            DateTime lastRunDateTime = DateTime.MinValue;
            Practice practice = new Practice(practicesXmlFile);
            List<Practice> practiceList = practice.SelectPracticeRecords(string.Empty);

            lastRunDateTime = GetLastRunDateTime();

            foreach (Practice practiceItem in practiceList)
            {
                Guid appId = practiceItem.ChildAppId;
                ReadHealthVaultItemTypes inboundAdapter = new ReadHealthVaultItemTypes(appId);

                inboundAdapter.GetPatients(Path.Combine(patientXmlFile, practiceItem.DataFolder + @"\" + Constants.PatientXmlFileName),
                        lastRunDateTime);
            }
        }

        /// <summary>
        /// Returns last run date time of the service.
        /// </summary>
        /// <returns>Returns date time value from file.</returns>
        private static DateTime GetLastRunDateTime()
        {
            DateTime lastRunDateTime = DateTime.MinValue;
            string fileName = SchedulerConfig.LastRunLogFile;
            string fullPath = Path.GetFullPath(fileName);

            if (File.Exists(fullPath))
            {
                using (StreamReader readLog = new StreamReader(fullPath))
                {
                    string dateTimeFromFile = String.Empty;
                    dateTimeFromFile = readLog.ReadLine();
                    if (!String.IsNullOrEmpty(dateTimeFromFile))
                    {
                        lastRunDateTime = DateTime.Parse(dateTimeFromFile);
                    }
                }
            }
            return lastRunDateTime;
        }
    }
}